<template>
  <j-modal :title="title" :width="1200" :visible="visible" :footer="null" @cancel="handleCancel" cancelText="关闭">
    <a-tabs v-model:activeKey="activeTab" @change="onTabChange">
      <a-tab-pane key="finished" tab="已作答" />
      <a-tab-pane key="unfinished" tab="未作答" />
    </a-tabs>
    <div class="result-table-wrap">
      <BasicTable @register="registerTable">
        <template #tableTitle>
          <a-space>
            <a-button v-if="activeTab==='finished'" type="primary" preIcon="ant-design:export-outlined" @click="onExportAll">导出</a-button>
            <a-button v-if="activeTab==='unfinished'" type="primary" preIcon="ant-design:export-outlined" @click="onExportUnfinished">导出</a-button>
            <a-button v-if="activeTab==='unfinished'" type="default" preIcon="ant-design:bell-outlined" @click="onNotifyUnfinished">钉钉通知</a-button>
          </a-space>
        </template>
      </BasicTable>
    </div>
  </j-modal>
</template>

<script lang="ts" setup>
  import { ref, defineExpose } from 'vue'
  import JModal from '/@/components/Modal/src/JModal/JModal.vue'
  import { BasicTable, useTable } from '/@/components/Table'
  import { defHttp } from '/@/utils/http/axios'
  import { useMethods } from '/@/hooks/system/useMethods'
  import { useMessage } from '/@/hooks/web/useMessage'

  const title = ref('查看成绩')
  const visible = ref(false)
  const mainId = ref<string>('')
  const activeTab = ref<'finished' | 'unfinished'>('finished')
  const { handleExportXls } = useMethods()
  const exportTitle = ref('未完成人员名单')
  const exportAllTitle = ref('人员名单')
  const { createMessage, createConfirm } = useMessage()

  // 已作答-列
  const finishedColumns = [
    {
      title: '一级部门',
      dataIndex: 'firstDept',
      width: 120,
    },
    {
      title: '二级部门',
      dataIndex: 'secondDept',
      width: 120,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      width: 120,
    },
    {
      title: '得分',
      dataIndex: 'fraction',
      width: 80,
      customRender: ({ record }) => `${record.fraction}分`,
    },
    {
      title: '用时',
      dataIndex: 'timeConsuming',
      width: 100,
      customRender: ({ record }) => {
        const seconds = record.timeConsuming || 0
        const minutes = Math.floor(seconds / 60)
        const remainingSeconds = seconds % 60
        return `${minutes}分${remainingSeconds}秒`
      },
    },
    {
      title: '已考试次数',
      dataIndex: 'submitNumber',
      width: 100,
    },
    {
      title: '已赠送积分',
      dataIndex: 'presented',
      width: 100,
    },
    {
      title: '考试时间',
      dataIndex: 'createTime',
      width: 160,
    },
  ]

  // 未作答-列（不包含：得分、用时、已考试次数、已赠送积分、考试时间）
  const unfinishedColumns = [
    {
      title: '一级部门',
      dataIndex: 'firstDept',
      width: 120,
    },
    {
      title: '二级部门',
      dataIndex: 'secondDept',
      width: 120,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      width: 120,
    },
  ]

  // 表格配置（根据 activeTab 动态请求 & 切换列）
  const [registerTable, { reload, setProps }] = useTable({
    title: '考试成绩列表',
    api: getListByTab,
    columns: finishedColumns,
    canResize: false,
    useSearchForm: false,
    pagination: {
      pageSize: 10,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
    },
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  })

  // 根据当前 Tab 加载对应列表
  async function getListByTab(params) {
    if (!mainId.value) return { records: [], total: 0 }

    const commonParams = {
      questionTypeId: mainId.value,
      column: 'createTime',
      order: 'desc',
      pageNo: params.pageNo || 1,
      pageSize: params.pageSize || 10,
    }

    try {
      if (activeTab.value === 'unfinished') {
        const res = await defHttp.get({
          url: '/hr/dtQuestionResult/unfinished/list',
          params: commonParams,
        })
        if (res && res.records) {
          return { records: res.records, total: res.total }
        }
        return { records: [], total: 0 }
      } else {
        const res = await defHttp.get({
          url: '/hr/dtQuestionResult/list',
          params: commonParams,
        })
        if (res && res.records) {
          return { records: res.records, total: res.total }
        }
        return { records: [], total: 0 }
      }
    } catch (error) {
      console.error('加载列表失败:', error)
      return { records: [], total: 0 }
    }
  }

  function onTabChange() {
    // 切换页签后切换列并刷新表格（修正：已作答=完整列，未作答=精简列）
    setProps({ columns: activeTab.value === 'unfinished' ? unfinishedColumns : finishedColumns })
    reload()
  }

  function open(record: Recordable) {
    mainId.value = record?.id
    visible.value = true
    // 每次打开默认切回“已作答”，并设置完整列
    activeTab.value = 'finished'
    setProps({ columns: finishedColumns })
    // 组装导出标题：{上级标题}未作答人员名单
    const parentTitle = (record && (record.title || record.name)) ? (record.title || record.name) : ''
    exportTitle.value = parentTitle ? `${parentTitle}未完成人员名单` : '未完成人员名单'
    exportAllTitle.value = parentTitle ? `${parentTitle}名单` : '名单'
    // 延迟一下再加载数据，确保弹窗完全打开
    setTimeout(() => {
      reload()
    }, 100)
  }

  function handleCancel() {
    visible.value = false
  }

  function onExportUnfinished(){
    if(!mainId.value){
      return
    }
    handleExportXls(exportTitle.value, '/hr/dtQuestionResult/unfinished/exportXls', { questionTypeId: mainId.value })
  }

  function onExportAll() {
    if(!mainId.value){
      return
    }
    handleExportXls(exportAllTitle.value, '/hr/dtQuestionResult/all/exportXls', { questionTypeId: mainId.value })
  }



  async function onNotifyUnfinished(){
    if(!mainId.value){
      return
    }
    createConfirm({
      iconType: 'warning',
      title: '钉钉通知',
      content: '是否向未完成人员发送钉钉通知？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await defHttp.get({ url: '/hr/dtQuestionResult/unfinished/send', params: { questionTypeId: mainId.value } })
        createMessage.success('通知已发送')
      }
    })
  }

  defineExpose({ open })
</script>

<style lang="less" scoped>
  .result-table-wrap {
    padding: 0;
  }
</style>
